package com.btex.app;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Util;
import com.bumptech.glide.Glide;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class OTCAddWeiAndZhi extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_menu)
    TextView mTvMenu;
    @BindView(R.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R.id.activity_add_name)
    EditText mActivityAddName;
    @BindView(R.id.activity_add_zhanghao)
    EditText mActivityAddZhanghao;
    @BindView(R.id.activity_add_imag)
    ImageView mActivityAddImag;
    @BindView(R.id.activity_add_lin_imag)
    LinearLayout mActivityAddLinImag;
    @BindView(R.id.activity_add_passwprd)
    EditText mActivityAddPasswprd;
    @BindView(R.id.activity_add_sure)
    TextView mActivityAddSure;
    @BindView(R.id.activity_add_imag_susses)
    ImageView mActivityAddImagSusses;
    @BindView(R.id.tv_otc_la)
    ImageView mTvOtcLa;
    @BindView(R.id.activity_add_tv_tianya)
    TextView mActivityAddTvTianya;
    private String mRealFilePath;
    private String mAbsolutePath;
    private MicroAVLIDialog mMicroAVLIDialog;
    public String type = "";
    private SharedPreferencesUtil mSharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otcadd_wei_and_zhi);
        ButterKnife.bind(this);
        mSharedPreferences = SharedPreferencesUtil.getSharedPreferences(this);
        mMicroAVLIDialog = new MicroAVLIDialog(this);
        String data = getIntent().getExtras().getString("data");

        if (!TextUtils.isEmpty(data)) {

            if (data.equals("支付宝")) {
                type = "alipay";
            } else if (data.equals("微信")) {
                type = "weixin";
            } else {
                type = "tianya";
                mActivityAddTvTianya.setText("天涯");
            }

        }
        mTvTitle.setText("添加" + data);
    }

    @Override
    public void setData() {

    }

    @Override
    public void onClick(View v) {

    }

    @OnClick({R.id.iv_back, R.id.activity_add_sure, R.id.activity_add_lin_imag})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.activity_add_sure:
                if (TextUtils.isEmpty(mActivityAddName.getText().toString().trim())) {
//                    SnackbarShow("姓名不能为空");
                    Util.showSnachBar(OTCAddWeiAndZhi.this, getResources().getColor(R.color.red),"姓名不能为空");
                    return;
                }

                if (TextUtils.isEmpty(mActivityAddZhanghao.getText().toString().trim())) {
//                    SnackbarShow("账号不能为空");
                    Util.showSnachBar(OTCAddWeiAndZhi.this, getResources().getColor(R.color.red),"账号不能为空");
                    return;
                }

                if (TextUtils.isEmpty(mRealFilePath)) {
//                    SnackbarShow("图片不能为空");
                    Util.showSnachBar(OTCAddWeiAndZhi.this, getResources().getColor(R.color.red),"图片不能为空");
                    return;
                }


                if (TextUtils.isEmpty(mActivityAddPasswprd.getText().toString().trim())) {
//                    SnackbarShow("交易密码不能为空");
                    Util.showSnachBar(OTCAddWeiAndZhi.this, getResources().getColor(R.color.red),"交易密码不能为空");
                    return;
                }


                Luban.with(this)
                        .load(new File(mRealFilePath))//传人要压缩的图片
                        .setCompressListener(new OnCompressListener() { //设置回调
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onSuccess(File file) {

                                mAbsolutePath = file.getAbsolutePath();
                                setOtcData();

                            }

                            @Override
                            public void onError(Throwable e) {

                            }
                        }).launch();    //启动压缩


//

                break;


            case R.id.activity_add_lin_imag:

                Matisse.from(OTCAddWeiAndZhi.this)
                        .choose(MimeType.allOf()) // 选择 mime 的类型
                        .countable(true)
                        .theme(R.style.Matisse_Dracula)
                        .maxSelectable(1) // 图片选择的最多数量
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f) // 缩略图的比例
                        .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                        .forResult(100); // 设置作为标记的请求码

                break;
        }
    }

    private void setOtcData() {


        String lang = "";
        boolean isEngilsh = mSharedPreferences.getBoolean("isEngilsh", false);

        if (isEngilsh) {
            lang = "en";
        } else {
            lang = "zh_cn";
        }

        mMicroAVLIDialog.show();


        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(this, SharedPreferencesUtil.getSharedPreferences(this));
        RequestParams params = new RequestParams();
        params.addBodyParameter("type", type);
        params.addBodyParameter("card_no", mActivityAddZhanghao.getText().toString().trim());
        params.addBodyParameter("img", new File(mAbsolutePath));
        params.addBodyParameter("trade_psw", mActivityAddPasswprd.getText().toString().trim());
        params.addBodyParameter("lang", lang);
        params.addHeader("myclient", "android");


        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.SET_PAY_CARD, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                mMicroAVLIDialog.dismiss();
                String result = responseInfo.result;
                Log.i("qkwnkqjwdn", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
//                        SnackbarShow(jsonObject.getString("info"));
                        Util.showSnachBar(OTCAddWeiAndZhi.this, getResources().getColor(R.color.bg_green),jsonObject.getString("info"));
                    } else {
//                        SnackbarShow(jsonObject.getString("info"));
                        Util.showSnachBar(OTCAddWeiAndZhi.this, getResources().getColor(R.color.red),jsonObject.getString("info"));
                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == RESULT_OK) {

            mActivityAddImagSusses.setVisibility(View.VISIBLE);
            mActivityAddImag.setVisibility(View.GONE);
            List<Uri> uris = Matisse.obtainResult(data);
            mRealFilePath = getRealFilePath(this, uris.get(0));
            Glide.with(this).load(mRealFilePath).into(mActivityAddImagSusses);

        }
    }


    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


//    private void SnackbarShow(String ms) {
//
//        Snackbar snackbar = ShortSnackbar(mRlTitle, ms, Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//        snackbar.show();
//    }
//
//    public static Snackbar ShortSnackbar(View view, String message, int messageColor, int backgroundColor) {
//        Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT);
//        setSnackbarColor(snackbar, messageColor, backgroundColor);
//        return snackbar;
//    }
//
//    /**
//     * 设置Snackbar文字和背景颜色
//     *
//     * @param snackbar
//     * @param messageColor
//     * @param backgroundColor
//     */
//    public static void setSnackbarColor(Snackbar snackbar, int messageColor, int backgroundColor) {
//        View view = snackbar.getView();
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            TextView message = (TextView) snackbar.getView().findViewById(R.id.snackbar_text);
//            //View.setTextAlignment需要SDK>=17
//            message.setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY);
//            message.setGravity(Gravity.CENTER);
//        }
//
//        if (view != null) {
//            view.setBackgroundColor(backgroundColor);
//            ((TextView) view.findViewById(R.id.snackbar_text)).setTextColor(messageColor);
//        }
//    }


}
